package main

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

/*
准备工作：
以root用户登录MySQL创建一个普通账户:
create user 'tester' identified by '123456';
登录：
mysql -utester -p'123456'
创建一个数据库：
create database test;
use test;
创建一个表：
create table if not exists student(
    id int not null auto_increment comment '主键自增id',
    name char(10) not null comment '姓名',
    province char(6) not null comment '省',
    city char(10) not null comment '城市',
    addr varchar(100) default '' comment '地址',
    score float not null default 0 comment '考试成绩',
    enrollment date not null comment '入学时间',
    primary key (id),unique key idx_name(name),
    key idx_location (province,city)
    ) default charset=utf8mb4 comment '学员基本信息';

插入几条测试数据:
insert into student (name, province,city,score,enrollment)
    values
    ('张三','北京','北京',60.1,'2021-03-05'),
    ('李四','河南','郑州',60.2,'2021-04-25'),
    ('小丽','四川','成都',60.3,'2021-03-10');
*/

type Student struct {
	ID         int       `gorm:"column:id;primaryKey" form:"id" binding:"required"`
	Name       string    `gorm:"column:name" form:"name"`
	Province   string    `gorm:"column:province" form:"province"`
	City       string    `gorm:"column:city"`
	Addr       string    `gorm:"column:addr"`
	Score      float32   `gorm:"column:score" form:"score"`
	Enrollment time.Time `gorm:"column:enrollment;type:date"`
}

//禁止把表名映射成复数形式
func (Student) TableName() string {
	return "student"
}

//根据学生id修改学生姓名
func SetStuName(engine *gin.Engine, db *gorm.DB) {
	engine.POST("/set_name", func(c *gin.Context) {
		id := c.PostForm("id")
		name := c.PostForm("name")
		var stu Student
		res := db.First(&stu, id) //根据主键找到对应的数据
		if res.RowsAffected == 0 {
			c.JSON(http.StatusNotFound, gin.H{"error": "records not found"})
			c.Abort()
		} else {
			if stu.Name != name {
				db.Model(&Student{}).Where("id=?", id).Update("name", name) //修改Student对应的表，指定条件，修改name列
				stu.Name = name
			}
			c.JSON(http.StatusOK, stu)
		}
	})
}

//根据学生id获取该学生的score
func GetStuScore(engine *gin.Engine, db *gorm.DB) {
	engine.GET("/stu/:id", func(c *gin.Context) {
		id := c.Param("id")
		var stu Student
		res := db.First(&stu, id) //根据主键找到对应的数据
		if res.RowsAffected == 0 {
			c.JSON(http.StatusNotFound, gin.H{"error": "records not found"})
			c.Abort()
		} else {
			c.String(http.StatusOK, "%.2f", stu.Score)
		}
	})
}

func main() {
	dsn := "tester:123456@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=True"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	engine := gin.Default()
	SetStuName(engine, db)
	GetStuScore(engine, db)

	engine.Run(":6666")
}
